package cn.ug.info.web.controller;

import cn.ug.aop.RequiresPermissions;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Order;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.config.Config;
import cn.ug.core.SerializeObjectError;
import cn.ug.core.login.LoginHelper;
import cn.ug.info.bean.ArticleBean;
import cn.ug.info.bean.ArticleClassBean;
import cn.ug.info.bean.status.YesStatus;
import cn.ug.info.service.ArticleClassService;
import cn.ug.info.service.ArticleService;
import cn.ug.util.UF;
import cn.ug.web.controller.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

import static org.springframework.web.bind.annotation.RequestMethod.*;

/**
 * 信息发布相关服务
 * @author kaiwotech
 */
@RestController
@RequestMapping("article")
public class ArticleController extends BaseController {

    @Resource
    private ArticleService articleService;
    @Resource
    private ArticleClassService articleClassService;
    @Resource
    private Config config;

    /**
     * 根据ID查找信息
     * @param accessToken	登录成功后分配的Key
     * @param id		    ID
     * @return			    记录集
     */
    @RequestMapping(value = "{id}", method = GET)
    public SerializeObject<ArticleBean> find(String accessToken, @PathVariable String id) {
        if(StringUtils.isBlank(id)) {
            return new SerializeObjectError("00000002");
        }
        ArticleBean entity = articleService.findById(id);
        if(null == entity || StringUtils.isBlank(entity.getId())) {
            return new SerializeObjectError("00000003");
        }
        return new SerializeObject<>(ResultType.NORMAL, entity);
    }

    /**
     * 新增信息（id为null、''）或修改信息（id不为空）
     * @param accessToken		登录成功后分配的Key
     * @param entity		    记录集
     * @return				    是否操作成功
     */
    @RequiresPermissions("sys:article:update")
    @RequestMapping(method = POST)
    public SerializeObject update(String accessToken, ArticleBean entity) {
        if(null == entity || StringUtils.isBlank(entity.getTitle())) {
            return new SerializeObjectError("12000101");
        }
        if(StringUtils.isBlank(entity.getArticleClassId())) {
            return new SerializeObjectError("12000102");
        }
        if(null == entity.getArticleClassTitle() || StringUtils.isBlank(entity.getArticleClassTitle())) {
            ArticleClassBean articleClassBean = articleClassService.findById(entity.getArticleClassId());
            if (null == articleClassBean || StringUtils.isBlank(articleClassBean.getId())) {
                return new SerializeObjectError("12000103");
            }
            entity.setArticleClassTitle(articleClassBean.getTitle());
        }
        int val;
        if(StringUtils.isBlank(entity.getId())) {
            // 添加发布人
            if(StringUtils.isBlank(entity.getSource())) {
                entity.setSource(LoginHelper.getLoginName());
            }
            val = articleService.save(entity);
        } else {
            val = articleService.update(entity.getId(), entity);
        }
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 删除信息
     * @param accessToken		登录成功后分配的Key
     * @param id			    ID数组
     * @return				    是否操作成功
     */
    @RequiresPermissions("sys:article:delete")
    @RequestMapping(method = DELETE)
    public SerializeObject delete(String accessToken, String[] id) {
        if(null == id || id.length <= 0) {
            return new SerializeObjectError("00000002");
        }

        int rows = articleService.deleteByIds(id);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 删除信息(逻辑删除)
     * @param accessToken		登录成功后分配的Key
     * @param id			    ID数组
     * @return				    是否操作成功
     */
    @RequiresPermissions("sys:article:remove")
    @RequestMapping(value = "remove", method = PUT)
    public SerializeObject remove(String accessToken, String[] id) {
        if(null == id || id.length <= 0) {
            return new SerializeObjectError("00000002");
        }

        int rows = articleService.removeByIds(id);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 查询列表
     * @param accessToken	    登录成功后分配的Key
     * @param order		        排序
     * @param articleClassId	分类ID
     * @param articleClassCode	分类编号
     * @param status			状态
     * @param keyword			关键字
     * @param containContent	包含Content 1：是 2：否
     * @return			        分页数据
     */
    @RequestMapping(value = "list", method = GET)
    public SerializeObject<List<ArticleBean>> list(String accessToken, Order order, String articleClassId, String articleClassCode, Integer status, String keyword, Integer containContent, String startTime, String endTime) {
        keyword = UF.toString(keyword);
        if(StringUtils.isNotBlank(articleClassCode) && StringUtils.isBlank(articleClassId)) {
            // 根据Code获取ID
            ArticleClassBean articleClassBean = articleClassService.findByCode(articleClassCode);
            if(null != articleClassBean) {
                articleClassId = articleClassBean.getId();
            }
        }
        List<ArticleBean> list = articleService.findList(order.getOrder(), order.getSort(), articleClassId, status, keyword, startTime, endTime);
        if(null != containContent && containContent.equals(YesStatus.NO)) {
            for (ArticleBean o : list) {
                o.setContent("");
            }
        }

        return new SerializeObject<>(ResultType.NORMAL, list);
    }

    /**
     * 查询数据
     * @param accessToken	    登录成功后分配的Key
     * @param order		        排序
     * @param page		        分页
     * @param articleClassId	分类ID(子栏目数据也会显示)
     * @param articleClassCode	分类编号
     * @param status			状态
     * @param keyword			关键字
     * @param containContent	包含Content 1：是 2：否
     * @return			        分页数据
     */
    @RequestMapping(method = GET)
    public SerializeObject<DataTable<ArticleBean>> query(String accessToken, Order order, Page page, String articleClassId, String articleClassCode, Integer status, String keyword, Integer containContent, String startTime, String endTime) {
        if(page.getPageSize() <= 0) {
            page.setPageSize(config.getPageSize());
        }
        keyword = UF.toString(keyword);
        if(StringUtils.isNotBlank(articleClassCode) && StringUtils.isBlank(articleClassId)) {
            // 根据Code获取ID
            ArticleClassBean articleClassBean = articleClassService.findByCode(articleClassCode);
            if(null != articleClassBean) {
                articleClassId = articleClassBean.getId();
            }
        }

        DataTable<ArticleBean> dataTable = articleService.query(order.getOrder(), order.getSort(), page.getPageNum(), page.getPageSize(), articleClassId, status, keyword, startTime, endTime);
        if(null != containContent && containContent.equals(YesStatus.NO)) {
            for (ArticleBean o : dataTable.getDataList()) {
                o.setContent("");
            }
        }
        return new SerializeObject<>(ResultType.NORMAL, dataTable);
    }

    /**
     * 验证是否存在
     * @param accessToken	    登录成功后分配的Key
     * @param entity	        验证参数
     * @return			        是否验证通过
     */
    @RequestMapping(value = "verify", method = GET)
    public SerializeObject verify(String accessToken, ArticleBean entity) {
        if(articleService.exists(entity, entity.getId())) {
            return new SerializeObjectError("12000105");
        }
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    @RequestMapping(value = "read", method = POST)
    public SerializeObject read(String accessToken,String id) {
        if(StringUtils.isBlank(id)) {
            return new SerializeObjectError("00000002");
        }
        articleService.read(id);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }
}
